package org.kojo.tdrm.servlet.auth;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.kojo.tdrm.utils.App;

public class AuthFilter implements Filter {
	private FilterConfig config = null;
	private static Logger log = Logger.getLogger(AuthFilter.class.getName());
	@Override
	public void destroy() {
		config = null;

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String userid = "";
		
		long before = System.currentTimeMillis();
		if (request instanceof HttpServletRequest) {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			userid = (String) httpServletRequest.getSession().getAttribute(
					App.USERID);
			log.fine("AuthFilter - Userid=" + userid);
			if (userid == null) {
				returnError(httpServletRequest, response,
						"User does not exist in session!");
				return;
			}
		}
		chain.doFilter(request, response);
		long after = System.currentTimeMillis();
		String name = "";

		if (request instanceof HttpServletRequest) {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			name = httpServletRequest.getRequestURI();
			userid = (String) httpServletRequest.getSession().getAttribute(
					App.USERID);

		}
		log.fine("RequestLog userid=" + userid + ", uri=" + name + ": "
				+ (after - before) + "ms");

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		this.config = arg0;

	}

	private void returnError(ServletRequest request, ServletResponse response,
			String errorString) throws ServletException, IOException {
		request.setAttribute("error", errorString);
		request.getRequestDispatcher("/login.jsp").forward(request, response);
	}
}
